package hys.wssoc.modules.info.utils;

import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ Author Eric
 * @ Description
 * @ Time 2024-03-2024/3/11-9:52
 */
public class CommonUtils {
    /**
     * 实现转换List中的Bean对象的工具类方法
     *
     * @param sourceList  需要转换的List
     * @param targetClass 需要转换的Bean对象类型
     * @return 返回转换完成之后的新List
     */
    public static <T, S> List<T> transformClass4List(List<S> sourceList, Class<T> targetClass) {
        if (sourceList == null || sourceList.isEmpty()) {
            throw new IllegalArgumentException("The source list must not be null or empty");
        }

        return sourceList.stream().map(source -> {
            try {
                T target = targetClass.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(source, target);
                return target;
            } catch (Exception e) {
                throw new RuntimeException("Failed to instantiate target class", e);
            }
        }).collect(Collectors.toList());
    }

    public static <T, S> T transformClass(S source, Class<T> targetClass) {
        try {
            T target = targetClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate target class", e);
        }
    }
}
